import { Injectable, Logger } from "@nestjs/common";
import { Cron, CronExpression } from "@nestjs/schedule";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, LessThan } from "typeorm";
import { PrivateMessageEntity } from "../../../entities/private-message.entity";

@Injectable()
export class PrivateMessageCleanupService {
  private readonly logger = new Logger(PrivateMessageCleanupService.name);

  constructor(
    @InjectRepository(PrivateMessageEntity)
    private readonly privateMessageRepository: Repository<PrivateMessageEntity>
  ) { }

  onModuleInit() {
    // this.cleanupOldReadMessages();
  }
  /**
   * 每小时执行一次，清理12小时前的已读私信消息
   * 使用 CronExpression.EVERY_HOUR 表示每小时执行
   */
  @Cron(CronExpression.EVERY_HOUR)
  async cleanupOldReadMessages() {
    try {
      this.logger.log("开始执行私信消息清理任务...");

      // 计算12小时前的时间
      const twelveHoursAgo = new Date();
      twelveHoursAgo.setHours(twelveHoursAgo.getHours() - 12);

      // 删除12小时前的已读消息
      const result = await this.privateMessageRepository.delete({
        isRead: 1, // 已读消息
        created_at: LessThan(twelveHoursAgo), // 创建时间早于12小时前
      });

      this.logger.log(`私信消息清理完成，删除了 ${result.affected} 条已读消息`);

      // 记录清理统计信息
      if (result.affected && result.affected > 0) {
        this.logger.log(`清理时间范围: ${twelveHoursAgo.toISOString()} 之前`);
        this.logger.log(`清理条件: 已读消息 + 12小时前 + 有效状态 + 正常状态`);
      }
    } catch (error) {
      this.logger.error("私信消息清理任务执行失败:", error);
    }
  }

  /**
   * 每天凌晨4点执行一次，清理30天前的未读私信消息
   * 使用 "0 4 * * *" 表示每天凌晨4点执行
   */
  @Cron("0 4 * * *")
  async cleanupOldUnreadMessages() {
    try {
      this.logger.log("开始执行未读私信消息清理任务...");

      // 计算30天前的时间
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

      // 删除30天前的未读消息
      const result = await this.privateMessageRepository.delete({
        isRead: 0, // 未读消息
        created_at: LessThan(thirtyDaysAgo), // 创建时间早于30天前
      });

      this.logger.log(
        `未读私信消息清理完成，删除了 ${result.affected} 条未读消息`
      );

      // 记录清理统计信息
      if (result.affected && result.affected > 0) {
        this.logger.log(`清理时间范围: ${thirtyDaysAgo.toISOString()} 之前`);
        this.logger.log(`清理条件: 未读消息 + 30天前`);
      }
    } catch (error) {
      this.logger.error("未读私信消息清理任务执行失败:", error);
    }
  }

  /**
   * 手动执行清理任务（用于测试或紧急清理）
   */
  async manualCleanup() {
    this.logger.log("手动执行私信消息清理任务...");
    await this.cleanupOldReadMessages();
  }

  /**
   * 手动执行未读消息清理任务（用于测试或紧急清理）
   */
  async manualCleanupUnread() {
    this.logger.log("手动执行未读私信消息清理任务...");
    await this.cleanupOldUnreadMessages();
  }

  /**
   * 获取清理统计信息
   */
  async getCleanupStats() {
    try {
      const twelveHoursAgo = new Date();
      twelveHoursAgo.setHours(twelveHoursAgo.getHours() - 12);

      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

      // 统计12小时前的已读消息
      const oldReadMessagesCount = await this.privateMessageRepository.count({
        where: {
          isRead: 1,
          created_at: LessThan(twelveHoursAgo),
        },
      });

      // 统计30天前的未读消息
      const oldUnreadMessagesCount = await this.privateMessageRepository.count({
        where: {
          isRead: 0,
          created_at: LessThan(thirtyDaysAgo),
        },
      });

      // 计算下次清理时间
      const now = new Date();
      const nextHourlyCleanup = new Date(now);
      nextHourlyCleanup.setHours(nextHourlyCleanup.getHours() + 1, 0, 0, 0);

      const nextDailyCleanup = new Date(now);
      nextDailyCleanup.setDate(nextDailyCleanup.getDate() + 1);
      nextDailyCleanup.setHours(4, 0, 0, 0);

      return {
        // 已读消息清理统计
        oldReadMessagesCount,
        readMessagesCutoffTime: twelveHoursAgo,
        nextHourlyCleanupTime: nextHourlyCleanup,

        // 未读消息清理统计
        oldUnreadMessagesCount,
        unreadMessagesCutoffTime: thirtyDaysAgo,
        nextDailyCleanupTime: nextDailyCleanup,
      };
    } catch (error) {
      this.logger.error("获取清理统计信息失败:", error);
      throw error;
    }
  }
}
